//
//  HMUserAccount.swift
//  Weibo22
//
//  Created by Apple on 16/12/3.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
//  账号模型
class HMUserAccount: NSObject, NSCoding {
    //  访问令牌
    var access_token: String?
    //  accesstoken的一个过期秒数
    var expires_in: TimeInterval = 0 {
        didSet {
            //  给过期秒数赋值的时候,设置过期日期
            //  过期日期 = 获取accesstoken的时间(当前时间) + 过期秒数
            
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
    
    //  过期日期
    var expiresDate: Date?
    
    //  用户id
    var uid: Int64 = 0
    //  用户的名字
    var name: String?
    //  用户的头像
    var avatar_large: String?
    
    //  kvc构造函数
    init(dic: [String: Any]) {
        super.init()
        setValuesForKeys(dic)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    //  归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        
    }
    
    //  解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    //  保存用户对象
    func saveUserAccount() {
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        //  归档操作
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
    }
    
    //  读取本地归档的用户对象
    class func loadUserAccount() -> HMUserAccount? {
         let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
         let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        
         return userAccount as? HMUserAccount
        
    
    }
    
    
    
}
